package server

import scala.util.control.NonFatal
import play.core.server.NettyServer
import java.io.File
import play.core.StaticApplication
import ws.very.util.lang.InputExitApp
import ws.very.util.lang.AnyInputExitableApp
import ws.very.util.lang.Args2SysPropApp
//sbt "~runMain server.Play -Dtest=2222"
object Play extends InputExitApp with AnyInputExitableApp with Args2SysPropApp {
  var server: Option[NettyServer] = None
  Option(System.getProperty("user.dir"))
    .map { applicationPath =>
      val applicationFile = new File(applicationPath)
      println(applicationFile)
      if (!(applicationFile.exists && applicationFile.isDirectory)) {
        println("Bad application path: " + applicationPath)
      } else {
        createServer(applicationFile).getOrElse(System.exit(-1))
      }
    }.getOrElse {
      println("No application path supplied")
    }

  def createServer(applicationPath: File): Option[NettyServer] = {
    // Manage RUNNING_PID file
    java.lang.management.ManagementFactory.getRuntimeMXBean.getName.split('@').headOption.map { pid =>
      println("Play server process ID is " + pid)
    }

    try {
      val server = new NettyServer(
        new StaticApplication(applicationPath),
        Option(System.getProperty("http.port")).fold(Option(9000))(p => if (p == "disabled") Option.empty[Int] else Option(Integer.parseInt(p))),
        Option(System.getProperty("https.port")).map(Integer.parseInt(_)),
        Option(System.getProperty("http.address")).getOrElse("0.0.0.0"))

      Runtime.getRuntime.addShutdownHook(new Thread {
        override def run {
          server.stop()
        }
      })

      Some(server)
    } catch {
      case NonFatal(e) => {
        println("Oops, cannot start the server.")
        e.printStackTrace()
        None
      }
    }

  }
}